//
//  EMWebView.m
//  EasyMoney
//
//  Created by 邓乐 on 2020/1/3.
//  Copyright © 2020 zh. All rights reserved.
//

#import "EMWebView.h"
#import "EMNetConfig.h"

static WKProcessPool *_sharedWKProcessPoolInstance = nil;

@implementation EMWebView

+ (WKProcessPool *)sharedProcessPool
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        if (_sharedWKProcessPoolInstance == nil) {
            _sharedWKProcessPoolInstance = [[WKProcessPool alloc] init];
        }
    });
    
    return _sharedWKProcessPoolInstance;
}

+ (instancetype)webviewWithFrame:(CGRect)frame
{
    WKUserContentController* userContentController = [WKUserContentController new];
    WKWebViewConfiguration* configuration = [WKWebViewConfiguration new];
    configuration.userContentController = userContentController;
    configuration.processPool = [EMWebView sharedProcessPool];
    
    WKUserScript *cookieScript = [[WKUserScript alloc] initWithSource: [EMWebView cookieString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
    
    WKPreferences* preferences = [WKPreferences new];
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    configuration.preferences = preferences;
    configuration.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
    
    return [[self alloc] initWithFrame:frame configuration:configuration];
}

- (nullable WKNavigation *)reload
{
    [self.configuration.userContentController removeAllUserScripts];
    
    WKUserScript * cookieScript = [[WKUserScript alloc] initWithSource:[EMWebView cookieString] injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [self.configuration.userContentController addUserScript:cookieScript];
    
    return [super reload];
}

+ (NSString *)cookieString
{
    NSMutableString *script = [NSMutableString string];
    [script appendString:@"var cookieNames = document.cookie.split('; ').map(function(cookie) { return cookie.split('=')[0] } );\n"];
    for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
        
        if ([cookie.value rangeOfString:@"'"].location != NSNotFound) {
            continue;
        }
        
        NSString *string = [NSString stringWithFormat:@"%@=%@;domain=%@;path=%@",
                            cookie.name,
                            cookie.value,
                            cookie.domain,
                            cookie.path ?: @"/"];
        
        [script appendFormat:@"if (cookieNames.indexOf('%@') == -1) { document.cookie='%@'; };\n", cookie.name, string];
    }
    return script;
}

@end
